package com.oj.config;

import com.oj.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.File;
@Slf4j
@Configuration
public class ThymeleafConfigurator {
    @Bean
    public ClassLoaderTemplateResolver templateResolver() {
        try {
            ApplicationHome h = new ApplicationHome(getClass());
            File jarF = h.getSource();
            File directory = new File(jarF.getParentFile().toString()+"/templates/freemarker");
            if(!directory.exists()){
                directory.mkdirs();
            }
            ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
            if (ResourceUtils.getURL("classpath:").getPath().startsWith("file:")) {
                templateResolver.setPrefix("file:" + jarF.getParentFile().toString() + "/templates/");
            } else {
                log.error("templateResolver not starts with file.");
                return null;
            }
            log.error("templateResolver ok.");
            templateResolver.setSuffix(".html");
            templateResolver.setTemplateMode(TemplateMode.HTML);
            templateResolver.setCharacterEncoding("UTF-8");
            templateResolver.setOrder(0);
            templateResolver.setCheckExistence(true);
            templateResolver.setCacheable(false);
            return templateResolver;
        }catch (Exception e) {
        }
        return null;
    }
}
